package org.rcloud.io.service.impl;

import org.rcloud.io.Utils.PageVo;
import org.rcloud.io.Utils.ResultVo;
import org.rcloud.io.mapper.UserMapper;
import org.rcloud.io.model.User;
import org.rcloud.io.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2019/1/26.
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVo findUserFromId(int id) {

        try {
            User user = userMapper.selectByPrimaryKey(id);
            return ResultVo.setOK(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.setError(e.getMessage());
        }

    }

    @Override
    public ResultVo findUserFromOpenid(String wxOpenid) {

        try {
            User user = userMapper.selectByKey(wxOpenid);
            return ResultVo.setOK(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.setError(e.getMessage());
        }

    }

    @Override
    public ResultVo update(User user) {

        if (user.equals("") || user == null) {
            return ResultVo.setError("传入数据为空");
        } else {
            try {
                userMapper.updateBywxOpenid(user);
                return ResultVo.setOK(null);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultVo.setError(e.getMessage());
            }
        }

    }

    @Override
    public ResultVo insert(String nickname) {
        try {
            User user = new User();
            user.setNickname(nickname);
            int i = userMapper.insertSelective(user);
            if (i > 0) {
                return ResultVo.setOK(null);
            } else {
                return ResultVo.setError("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.setError(e.getMessage());
        }
    }

    @Override
    public PageVo<User> selectLikeRealName(String realname) {
        try {
            List<User> list = userMapper.selectLikeRealName("%" + realname + "%");
            return PageVo.setOk(list);
        } catch (Exception e) {
            e.printStackTrace();
            return PageVo.setError(e.getMessage());
        }
    }

}
